// 定义初始状态
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
function MyPromise(fn) {
  const self = this;
  this.state = PENDING;
  this.value = null;
  this.resolvedCallbacks = [];
  this.rejectedCallbacks = [];
  // 定义两个状态函数
  function resolve(value) {
    // 判断一下进来的值是否属于当前原型链上 如果是的话直接返回then
    if (value instanceof MyPromise) {
      return value.then(resolve, reject);
    }
    // 进来这里说明请求已经执行完了，状态改变
    setTimeout(() => {
      // 等于PENDING时改变，否则不改变状态
      if (self.state === PENDING) {
        self.state = RESOLVED;
        // 赋值
        self.value = value;
        self.resolvedCallbacks.forEach(callback => {
          callback(value);
        });
      }
    }, 0);
  }
  function reject(value) {
    setTimeout(() => {
      // 同理
      if (self.state === PENDING) {
        self.state = REJECTED;
        // 赋值
        self.value = value;
        // 添加then回调函数 里面是些什么东西呢
        self.rejectedCallbacks.forEach(callback => {
          callback(value);
        });
      }
    }, 0);
  }
  try {
    // 调用传进来的函数 把两个状态函数传进去
    fn(resolve, reject);
  } catch (error) {
    reject(error);
  }
}

// 解决链式调用.then 在原型上加方法 then接收两个函数,第一个函数为err,第二个函数为res
MyPromise.prototype.then = function (onResolve, onReject) {
  // 判断传递进来的是否是两个函数
  onReject = typeof onReject === 'function' ? onReject : value => value;
  onResolve =
    typeof onResolve === 'function' ? onResolve : error => new Error(error);
  const self = this;
  return new MyPromise((resolve, reject) => {
    console.log('self.state ==> ', self.state);
    if (self && self.state === PENDING) {
      // self.resolvedCallbacks.push(onResolve)
      self.resolvedCallbacks.push(value => {
        try {
          const res = onResolve(value);
          res instanceof MyPromise ? res.then(resolve, reject) : resolve(res);
        } catch (error) {
          reject(error);
        }
      });
      self.rejectedCallbacks.push(value => {
        try {
          const res = onReject(value);
          res instanceof MyPromise ? res.then(resolve, reject) : reject(res);
        } catch (error) {
          reject(error);
        }
      });
    }
    if (self.state === RESOLVED) {
      setTimeout(() => {
        try {
          const res = onResolve(self.value);
          res instanceof MyPromise ? res.then(resolve, reject) : resolve(res);
        } catch (err) {
          reject(err);
        }
      }, 0);
    }
    if (self.state === REJECTED) {
      setTimeout(() => {
        try {
          const res = onReject(self.value);
          res instanceof MyPromise ? res.then(resolve, reject) : reject(res);
        } catch (err) {
          reject(err);
        }
      }, 0);
    }
  });
};

MyPromise.prototype.all = function (promises) {
  if (!Array.isArray(promises)) {
    return new Error('必须要一个数组');
  }
  return new Promise((resolve, reject) => {
    const res = [];
    for (let index = 0; index < promises.length; index++) {
      new Promise.resolve(promises[index])
        .then(value => {
          res[index] = value;
          if (res.length === promises.length) {
            resolve(res);
          }
        })
        .catch(err => {
          reject(err);
        });
    }
  });
};

const testFunc = async () => {
  console.log(1);
  const pr = new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve(3);
    }, 1000);
  })
    .then(
      res => {
        console.log('prres ==> ', res);
      },
      err => {
        console.error('err ==> ', err);
      }
    )
    .then(res => {
      console.log('res222', res);
    });
  console.log('pr ==> ', pr);
  // pr.then((res) => {
  //   console.log('resthen ==> ', res)
  // })
  console.log(2);
};
testFunc();
